/**
 * Copyright (C) 2012 The SkyTvOS Project
 * <p/>
 * Version     Date           Author
 * ─────────────────────────────────────
 * 2014年11月10日         Root.Lu
 */

package com.tianci.appstore.framework;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

import com.tianci.appstore.utils.AppDebug;
import com.tianci.appstore.utils.AsyncTask;

public abstract class AppBaseService extends Service {
    private IBinder binder = null;

    @Override
    public final void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();
        new Thread(new Runnable() {
            @Override
            public void run() {
                // TODO Auto-generated method stub
                synchronized (AppBaseService.this) {
                    long st = System.currentTimeMillis();
                    binder = start();
                    long end = System.currentTimeMillis();
                    AppDebug.debug("<service start>" + AppBaseService.this.getClass().getName()
                            + " start cost:" + (end - st) + "ms!");
                    AppBaseService.this.notify();
                }
            }
        }, AppBaseService.this.getClass().getSimpleName() + " create thread").start();
    }

    @Override
    public final IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        synchronized (this) {
            if (binder == null)
                try {
                    wait();
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
        }
        return binder;
    }

    protected abstract IBinder start();

    protected static void runOnThread(Runnable r) {
        AsyncTask.runOnThread(r);
    }
}
